package cn.virens.database.serviceimpl.sys;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;

import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.enums.MessageState;
import cn.virens.database.mysql.mapper.sys.SysMessageMapper;
import cn.virens.database.mysql.model.sys.SysMessage;
import cn.virens.database.service.sys.SysMessageService;
import cn.virens.exception.APIException;

@Service
public class SysMessageServiceImpl extends BaseServiceImpl<SysMessage, SysMessageMapper> implements SysMessageService {
	@Autowired
	public SysMessageServiceImpl(SysMessageMapper mBaseMapper) {
		super(mBaseMapper);
	}

	@Override
	@Transactional(readOnly = false)
	public SysMessage read(Integer id) throws APIException {
		SysMessage result = selectOne(id);

		if (result != null) {
			// mBaseMapper.updateState(id, MessageState.READ.toInt());
		} else {
			throw new APIException("NULL", "消息不存在");
		}

		return result;
	}

	@Override
	@Transactional(readOnly = true)
	public PageInfo<SysMessage> notifications(String account) {
		PageInfo<SysMessage> result = new PageInfo<>();

		ExampleWrapper example = new ExampleWrapper();
		example.orderBy("createTime").desc();
		example.selectProperties("id", "account", "title", "type", "state", "link", "send");
		example.createCriteria((criteria) -> {
			criteria.andEqualTo("account", account);
			criteria.andEqualTo("state", MessageState.UN_READ.toInt());
		});

		// 查询未读消息总数
		result.setTotal(mBaseMapper.selectCountByExample(example));
		// 如果有未读消息，查询最新5条
		if (result.getTotal() > 0) {
			result.setList(mBaseMapper.selectByExampleAndRowBounds(example, new RowBounds(0, 5)));
		}

		return result;
	}

	@Override
	protected List<?> doPageQuery(Map<String, Object> param) throws APIException {
		ExampleWrapper example = new ExampleWrapper();
		example.orderBy("createTime").desc();

		example.selectProperties("id", "account", "title", "type", "state", "link", "send");
		if (param != null) example.createCriteria((criteria) -> {
			if (param.containsKey("state")) criteria.andEqualTo("state", param.get("state"));
			if (param.containsKey("account")) criteria.andEqualTo("account", param.get("account"));

			if (param.containsKey("send")) criteria.andLike("send", String.valueOf(param.get("send")) + "%");
			if (param.containsKey("title")) criteria.andLike("title", "%" + String.valueOf(param.get("title")) + "%");

		});

		return mBaseMapper.selectByExample(example);
	}

	@Override
	protected Class<SysMessage> getGenericSuperclass() {
		return SysMessage.class;
	}
}
